package com.oobi.showlive.datastore.service.auth;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oobi.showlive.datastore.data.conn.PMF;
import com.oobi.showlive.datastore.data.reg.Registration;
import com.oobi.showlive.datastore.service.reg.Register;

@SuppressWarnings({"serial"})
public class ValidateUserServlet extends HttpServlet{
	
	PersistenceManager pm = PMF.get().getPersistenceManager();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		 resp.setContentType("text/html");
		    PrintWriter out = resp.getWriter();
		 // Get the user's name and password
	    String name = req.getParameter("name");
	    String passwd = req.getParameter("passwd");
	    
	    if(notEmpty(name) && notEmpty(passwd)) {
	    	Query q = pm.newQuery(Registration.class);
	    	q.setFilter("userName == userNameParam");
	    	q.declareParameters("String userNameParam");
	    	List<Registration> registration = (List<Registration>)q.execute(name);
	    	if(registration.size()>0){
	    		Registration currReg = registration.get(0);
	    		if(currReg.getPassword().equals(passwd)) {
	    			resp.setStatus(HttpServletResponse.SC_OK);
	    			out.println("Authentication Successful");
	    		} else {
	    			resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
	    		}
	    	} else {
	    		resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
	    	}
	    } else {
	    	resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
	    }
	}
	
	 protected boolean notEmpty(String str) {
		    if(str!=null && !"".equals(str) )
		    	return true;  
		    else 
		    	return false;
     }

}
